package handler

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	pb "mpps/services/srv-ProgramLatest/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/program"
)

type ProgramLatest struct {
}

func NewProgramLatest() *ProgramLatest {
	return &ProgramLatest{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *ProgramLatest) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Mode) <= 0 || len(req.FileType) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType != program.Js.String() && req.FileType != program.Program.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.Mode != program.Dev.String() && req.Mode != program.Preview.String() && req.Mode != program.Prod.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType == program.Program.String() && len(req.ProgramId) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	model := program.MiniProgram{}
	var where string
	switch req.FileType {
	case program.Program.String():
		where = fmt.Sprintf("program_id = '%v' AND mode = '%v' AND file_type = '%v'", req.ProgramId, req.Mode, req.FileType)
	case program.Js.String():
		where = fmt.Sprintf("mode = '%v' AND file_type = '%v'", req.Mode, req.FileType)
	}
	result := dao.GetDB(ctx).
		Model(&program.MiniProgram{}).
		Where(where).
		Order("created_at desc").
		Limit(1).
		Find(&model)
	if result == nil || result.RowsAffected <= 0 {
		return errors.New(common.ErrGetLatest.Message)
	}
	jb, err := json.Marshal(model)
	if err != nil {
		return errors.New(common.ErrGetLatest.Message)
	}
	json.Unmarshal(jb, rsp)
	return nil
}
